package com.softeem.score.manager.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softeem.score.common.exception.MyException;
import com.softeem.score.manager.mapper.StudentMapper;
import com.softeem.score.manager.mapper.SysUserMapper;
import com.softeem.score.manager.mapper.SysUserRoleMapper;
import com.softeem.score.manager.mapper.TeacherMapper;
import com.softeem.score.manager.service.SysUserService;
import com.softeem.score.model.dto.AssginRoleDto;
import com.softeem.score.model.dto.LoginDto;
import com.softeem.score.model.dto.SysUserDto;
import com.softeem.score.model.entity.school.Student;
import com.softeem.score.model.entity.system.SysUser;
import com.softeem.score.model.vo.common.ResultCodeEnum;
import com.softeem.score.model.vo.system.LoginVo;
import com.softeem.score.utils.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //用户登录
    @Override
    public LoginVo login(LoginDto loginDto) {
        //获取输入验证码和存储到redis的key名称  loginDto获取到
        String captcha = loginDto.getCaptcha();
        String key = loginDto.getCodeKey();
        //2 根据获取的redis里面key ，查询redis里面存储验证码
        // set("user:validate"+key
        String redisCode = redisTemplate.opsForValue().get("user:validate:" + key);
        //3 比较输入的验证码和 redis存储验证码是否一致
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode, captcha)) {
            //4 如果不一致，提示用户，校验失败
            throw new MyException(ResultCodeEnum.VALIDATECODE_ERROR);//VALIDATECODE_ERROR(202 , "验证码错误") ,
        }
        //5 如果一致，删除redis里面验证码
        redisTemplate.delete("user:validate:" + key);
        //1 获取提交用户名，loginDto获取到
        String userName = loginDto.getUserName();
        //2 根据用户名查询数据库表 sys_user表
        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(userName);
        //3 如果根据用户名查不到对应信息，用户不存在，返回错误信息
        if (sysUser == null) {
//            throw new RuntimeException("用户名不存在");
            throw new MyException(ResultCodeEnum.USER_NOT_EXISTS);
        }
        //4 如果根据用户名查询到用户信息，用户存在
        //5 获取输入的密码，比较输入的密码和数据库密码是否一致
        String database_password = sysUser.getPassword();
        String input_password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes(StandardCharsets.UTF_8));
        //比较
        if (!input_password.equals(database_password)) {
            throw new MyException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 获取请求相关参数
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        sysUserMapper.updateIpconf(sysUser.getId(), request.getRemoteAddr());
        //6 如果密码一致，登录成功，如果密码不一致登录失败
        //7 登录成功，生成用户唯一标识token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //8 把登录成功用户信息放到redis里面
        // key : token   value: 用户信息
        redisTemplate.opsForValue().set("user:login:" + token, JSON.toJSONString(sysUser), 300, TimeUnit.DAYS);
        //9 返回loginvo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    //获取当前登录用户信息
    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        return JSON.parseObject(userJson, SysUser.class);
    }

    //用户退出
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login:" + token);
    }

    //1 用户条件分页查询接口
    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum,
                                        Integer pageSize,
                                        SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> list = sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    //2 用户添加
    @Transactional
    @Override
    public void saveSysUser(SysUser sysUser) {
        //1 判断用户名不能重复
        String userName = sysUser.getUsername();
        SysUser dbSysUser = sysUserMapper.selectUserInfoByUserName(userName);
        if (dbSysUser != null) {
            throw new MyException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        //2 输入密码进行加密
        String md5_password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes(StandardCharsets.UTF_8));
        sysUser.setPassword(md5_password);
        //设置status值  1 正常 0 不可用
        sysUser.setStatus(1);
        sysUserMapper.saveSysUser(sysUser);
    }

    //3 用户修改
    @Transactional
    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser);
    }

    //4 用户删除
    @Transactional
    @Override
    public void deleteById(Long userId) {
        sysUserMapper.deleteById(userId);
    }


    @Transactional
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        //1 根据userId删除用户之前分配角色数据
        sysUserRoleMapper.deleteByUserId(assginRoleDto.getUserId());
        //2 重新分配新数据
        sysUserRoleMapper.doAssign(assginRoleDto.getUserId(), assginRoleDto.getRoleIdList());
    }

    //跟新用户状态
    @Transactional
    @Override
    public void updateStatus(Long userId, Integer status) {
        sysUserMapper.updateStatus(userId, status);
    }

    @Transactional
    @Override
    public void updateAvatar(Long userId, String avatar, String token) {
        sysUserMapper.updateAvatar(userId, avatar);
        // 先获取原有的值
        String jsonValue = redisTemplate.opsForValue().get("user:login:" + token);
        // 将 JSON 字符串转换为对象
        SysUser sysUser = JSON.parseObject(jsonValue, SysUser.class);
        // 更新需要修改的字段
        if (sysUser != null) {
            sysUser.setAvatar(avatar);
        }
        // 将更新后的对象转换为 JSON 字符串
        String updatedJsonValue = JSON.toJSONString(sysUser);
        // 将更新后的值重新设置到 Redis 中
        redisTemplate.opsForValue().set("user:login:" + token, updatedJsonValue, 300, TimeUnit.DAYS);
    }

    @Transactional
    @Override
    public void updatenewPassword(String oldPassword, String newPassword) {
        SysUser sysUser = AuthContextUtil.get();// 获取当前登录用户
        if (sysUser != null) {
            String oldpassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes(StandardCharsets.UTF_8));
            if (!oldpassword.equals(sysUser.getPassword())) {
                throw new MyException(ResultCodeEnum.PASSWORD_ERROR);
            }
            String newpassword = DigestUtils.md5DigestAsHex(newPassword.getBytes(StandardCharsets.UTF_8));
            sysUser.setPassword(newpassword);
            sysUserMapper.updateSysUser(sysUser);
        } else {
            throw new MyException(ResultCodeEnum.LOGIN_AUTH);
        }
    }

    @Transactional
    @Override
    public void updateMobile(String username, String mobile, String code, String token) {
        if (!mobile.matches("^1[3-9]\\d{9}$")) {
            throw new MyException(ResultCodeEnum.MOBILE_ERROR);
        }
        if (!code.equals(redisTemplate.opsForValue().get(mobile))) {
            throw new MyException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        sysUserMapper.updateMobile(username, mobile);
        // 先获取原有的值
        String jsonValue = redisTemplate.opsForValue().get("user:login:" + token);
        // 将 JSON 字符串转换为对象
        SysUser sysUser = JSON.parseObject(jsonValue, SysUser.class);
        // 更新需要修改的字段
        if (sysUser != null) {
            sysUser.setMobile(mobile);
        }
        // 将更新后的对象转换为 JSON 字符串
        String updatedJsonValue = JSON.toJSONString(sysUser);
        // 将更新后的值重新设置到 Redis 中
        redisTemplate.opsForValue().set("user:login:" + token, updatedJsonValue, 300, TimeUnit.DAYS);
    }

    //重置密码
    @Transactional
    @Override
    public void restartPassword(String username, String mobile, String code) {
        if (!mobile.matches("^1[3-9]\\d{9}$")) {
            throw new MyException(ResultCodeEnum.MOBILE_ERROR);
        }
        if (!code.equals(redisTemplate.opsForValue().get(mobile))) {
            throw new MyException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        if (sysUserMapper.findByUsernameAndMobile(username,mobile) != null) {
            if (studentMapper.findStudentIdsByStudentNumber(username) > 0) {
                Student student = studentMapper.findByStudentNumber(username);
                String idCardLastSixDigits = student.getIdCard().substring(student.getIdCard().length() - 6);
                String encryptedPassword = DigestUtils.md5DigestAsHex(idCardLastSixDigits.getBytes(StandardCharsets.UTF_8));
                sysUserMapper.restartPassword(encryptedPassword, username);
            } else if (teacherMapper.findTeacherByTeacherNumber(username) > 0) {
                //2 输入密码进行加密
                String md5_password = DigestUtils.md5DigestAsHex(username.getBytes(StandardCharsets.UTF_8));
                sysUserMapper.restartPassword(md5_password, username);
            }
        } else {
            throw new MyException(ResultCodeEnum.USER_NOT_EXISTS);
        }
    }
}